<template>
  <div class="content">
    <div class="list_box">
      <div class="box">
        <div @click="changeTc(item, index)" class="box2" v-for="(item, index) in list" :key="index">
          <div class="msg">
            <p class="t_t">发布条数（{{ item.number }}条）</p>
            <p class="text">{{ item.introduction }}</p>
          </div>
          <div class="right">
            <p class="price">{{ item.price }}元</p>
          </div>
          <p class="on" v-if="index == tcIndex">
            <img src="@/static/gou.png" alt="" />
            <span>
              <u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
            </span>
          </p>
        </div>
      </div>
    </div>

    <div class="totle_price">
      <p>小计</p>
      <p class="price" v-if="tabMsg.price">¥{{ tabMsg.price }}</p>
    </div>
    <div class="play_box">
      <p class="title">支付方式</p>
      <div class="radio-group-container">
        <radio-group v-model="selectedOption" @change="changePlayType">
          <label class="radio-label">
            <div class="text">
              <img src="@/static/wx_play.png" alt="" />
              微信支付
            </div>
            <!-- <radio v-model="option.value" /> -->
            <img class="gx" src="@/static/xz.png" alt="" />
          </label>
        </radio-group>
      </div>
      <u-button :disabled="isDisable" loadingMode="circle" :loading="isDisable" loadingText="支付中..." type="primary"
        text="立即支付" @click="submitplay">
      </u-button>
    </div>

    <div class="anniu">
        <wx-open-launch-weapp id="launch-btn" appid="wx066f87c1fd98e952" username="gh_0048934ca6a7" path='pages/index/index'>
          <script type="text/wxtag-template">
          <style scoped>.btn {display: block;width: 100%;height: 96rpx;line-height: 96rpx;border-radius: 100rpx;background: #23ac39;font-size: 32rpx;text-align: center;font-weight: 500;color: #fff;border: none;}</style>
          <button class="btn">返回小程序</button>
          </script>
        </wx-open-launch-weapp>
      </div>
  </div>
</template>

<script>
import wx from "@/utils/jweixin-1.6.0.js"
import api from "@/api"
import {
  setUserToken,
  getUserToken,
  setUserRefreshToken
} from "@/utils/auth";
export default {
  data() {
    return {
      selectedOption: "1", // 用于v-model绑定，存储选中的值
      isDisable: false, // 提交
      tcIndex: 0,
      list: [],
      tabMsg: {}
    }
  },
  methods: {
    // 选择支付方式
    changePlayType(e) {
      console.log(e)
    },

    changeTc(item, index) {
      console.log(item, index)
      this.tabMsg = item
      this.tcIndex = index
    },

    // 获取列表
    getList() {
      api.user.list_by_ids().then((res) => {
        if (res.code == 200) {
          res.data.map((item) => {
            item.price = (item.price / 100).toFixed(2)
          })
          this.list = res.data
          this.tabMsg = res.data[0]
        }
      })
    },

    // 创建订单-发起支付
    async submitplay() {
      if (!getUserToken()) {
        var fromUrl = location.href; // 当前页面的URL
        var appId = 'wx3d88709920c7b53f'; // 公众号appid
        var redirectUri = encodeURIComponent(fromUrl); // 对 redirect_uri 进行编码
        var state = 'STATE'; // 一个随机生成的字符串，用于防止 CSRF 攻击
        var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' +
            'appid=' + appId +
            '&redirect_uri=' + redirectUri +
            '&response_type=code' +
            '&scope=snsapi_userinfo' +
            '&state=' + state;
        location.href = url;

      } else {
        let data = {
          spuId: this.tabMsg.id,
          count: 1,
        }
        let payOrderId  = ''
        await api.user.order_create(data).then(res => {
          if (res.code == 200) {
            payOrderId  = res.data.payOrderId
          } else {
            this.$toast(res.msg)
          }
        })
        if (payOrderId) {
          let canshu = {
            type: 31,
            id: payOrderId,
            channelCode: "wx_pub",
          }
          await api.user.pay_order(canshu).then(res => {
            if (res.code == 200) {
              let payObj = JSON.parse(res.data.displayContent)
              // this.$toast(res.data.appId)
              WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                  "appId": 'wx3d88709920c7b53f', // 公众号ID，由商户传入（appId为当前服务商号绑定的appid）     
                  "timeStamp": payObj.timeStamp, // 时间戳，自1970年以来的秒数     
                  "nonceStr": payObj.nonceStr, // 随机字符串，不长于32位  
                  "package": payObj.packageValue, // 统一下单接口返回的prepay_id参数值，提交格式如：prepay_id=***     
                  "signType": payObj.signType, // 微信签名方式：默认为MD5，支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致     
                  "paySign": payObj.paySign // 微信签名 
                },
                function (res) {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    uni.navigateTo({
                      url: '/pages/success/index'
                    });
                  }
                }
              );
            }else {
              this.$toast(res.msg)
            }
          })
        }
      }
    },
  },
  onLoad(options) {

  },
  async onShow() {
    let url = location.href
    if (!getUserToken() && url.indexOf('code') != -1) {
      let code = url.split('?')[1].split('=')[1].split('&')[0]
      console.log(code)
      let data = {
        type: 31,
        code,
        state: "default"
      }
      console.log(data)
      await api.user.social_login(data).then(res => {
        if (res.code == 200) {
          setUserToken(res.data.accessToken)
          setUserRefreshToken(res.data.refreshToken)
        } else {
          this.$toast(res.msg)
        }
      })
    }

    await api.user.getJsapiSignature(url).then(res=>{
        if (res.code == 200) {
          wx.config({
            debug: false,
            appId: res.data.appId, // 公众号
            timestamp: res.data.timestamp, // 
            nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
            signature: res.data.signature, // 必填，签名
            jsApiList: [
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
            "checkJsApi",
            "scanQRCode"
            ],
            openTagList: ["wx-open-launch-weapp"],
          });
          wx.ready(function (res) {
            var btn = document.getElementById("launch-btn");
            btn.addEventListener("ready", function (e) {});
            btn.addEventListener("launch", function (e) {});
            btn.addEventListener("error", function (e) {
            alert('error');
            alert(JSON.stringify(e));
            });
            console.log('成功', res)
          });
          wx.error(function (res) {
            console.log('失败', res);
          })
        }
      })
    this.getList()
  },
}
</script>

<style lang="scss" scoped>
.content {
  background: #f7f7f7;

  .list_box {
    padding: 30rpx;

    .box2 {
      padding: 0 30rpx;
      height: 87px;
      border-radius: 5px;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 22rpx;
      position: relative;

      .on {
        position: absolute;
        top: 0;
        right: 0;

        img {
          width: 70rpx;
          height: 70rpx;
        }

        span {
          position: absolute;
          top: 4rpx;
          right: 0;
        }
      }

      .msg {
        .t_t {
          font-size: 28rpx;
          font-weight: bold;
          color: #3d3d3d;
        }

        .text {
          font-size: 28rpx;
          color: #999999;
          margin-top: 16rpx;
        }
      }

      .right {
        .price {
          color: #ff5218;
          font-size: 28rpx;
          font-weight: bold;
          text-align: right;
        }
      }
    }
  }

  .totle_price {
    margin: 0 39rpx;
    border-bottom: 1px solid #d8d8d8;
    padding-bottom: 18rpx;
    display: flex;
    justify-content: space-between;
    font-size: 32rpx;
    color: #333;

    .price {
      font-weight: bold;
    }
  }

  .play_box {
    margin: 24rpx 30rpx;

    .title {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 30rpx;
    }

    .radio-group-container {
      display: flex;
      flex-direction: column;
      margin-bottom: 30rpx;

      .radio-label {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        /* 根据需要调整间距 */
      }

      .text {
        font-size: 32rpx;
        color: #333;
        display: flex;
        align-items: center;

        img {
          width: 40rpx;
          height: 40rpx;
          margin-right: 10rpx;
        }

        span {
          color: #999;
          font-size: 24rpx;
        }
      }

      .gx {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  /deep/ .u-button {
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 100rpx;
    background: #23ac39;
    font-size: 32rpx;
    text-align: center;
    font-weight: 500;
    color: #fff;
    border: none;
  }
}

.anniu{
  display: flex;
  justify-content: center;
  margin:200rpx 32rpx 0 32rpx;
  p{
    width: 40%;
    height: 80rpx;
    line-height: 80rpx;
    color: #F2DBA8;
    background-color: #2F2D2D;
    border-radius: 10rpx;
    text-align: center;
    font-size: 30rpx;
    &:first-child{
      background-color: #fff;
      border: 2rpx solid #F2DBA8;
      color: #F2DBA8;
      box-sizing: border-box;
      // margin-right: 22rpx;
      // width: 70%;
    }
  }
}
</style>
